<template>
  <div class="con">
    <div class="contbox6_10">
      <div class="titlelist6_10">活动管理 / 商户拉新 </div>
      <div class="content">
        <div class="relus">
          活动配置说明：普通代理新增拓展商户拉新活动，拓展的商户绑定活动商品后，商户的交易量达标给与奖励。
          <img @click="relues" src="../../assets/images/sm.png" />
        </div>
        <div class="jibenInfo">商户拉新奖励</div>
        <div class="listWrap">
          <div class="list">
            <div class="name">活动名称</div>
            <el-input
              :disabled="dis == 'y'"
              v-model="form.activeName"
              placeholder="请输入内容"
              maxlength="30"
              style="width: 300px"
            ></el-input>
          </div>
          <!-- <div class="list">
            <div class="name">参与对象</div>
            <el-select
              :disabled="dis == 'y' || diss == 'z'"
              v-model="form.objectType"
              placeholder="请选择"
              style="width: 278px"
            >
              <el-option
                v-for="item in objectType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="list" v-if="form.objectType == '1'">
            <div class="name">选择团队</div>
            <el-cascader
              @remove-tag="delTag"
              ref="cascaderAddr"
              v-model="form.officeUids"
              :disabled="dis == 'y' || diss == 'z'"
              :options="options"
              :props="{ multiple: true, checkStrictly: true, emitPath: false }"
              clearable
            ></el-cascader>
          </div> -->
          <div class="list">
            <div class="name">参与活动品牌</div>
            <el-select
              v-model="form.Brand"
              @change="pinChange"
              placeholder="请选择"
              :disabled="diss"
            >
              <el-option
                v-for="item in optionsBrand"
                :key="item.uid"
                :label="item.channelName"
                :value="item.uid"
              >
              </el-option>
            </el-select>
          </div>
          <div class="list">
            <div class="name">活动商品</div>
            <el-select
              @remove-tag="delTag"
              value-key="productUid"
              @change="
                xingType(form.BrandTypeNum);
                $forceUpdate();
              "
              placeholder="请选择商品"
              v-model="form.BrandTypeNum"
              multiple
              collapse-tags
            >
              <el-option
                label="全选"
                value="全选"
                @click.native="selectAll"
                :disabled="diss"
              ></el-option>
              <el-option
                v-for="item in optionsBrandTypeNum"
                :key="item.productUid"
                :label="item.productName"
                :value="item.productUid"
                :disabled="diss"
              >
              </el-option>
            </el-select>
          </div>
          <div class="list">
            <div class="name">考核时间</div>
            <el-date-picker
              :disabled="dis == 'y'"
              @change="shijian"
              @input="daterangeChange"
              v-model="form.timers"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              style="width: 300px"
              :picker-options="pickerOptions"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
          <div class="list">
            <div class="name">奖励发放时间</div>
            <el-date-picker
              :disabled="dis == 'y'"
              value-format="yyyy-MM-dd"
              v-model="form.rewardDate"
              type="date"
              placeholder="选择日期"
              style="width: 200px !important"
            ></el-date-picker>
          </div>
        </div>
        <div class="jibenInfo">活动规则</div>
        <div class="targetSet">
          <div
            class="targetSet"
            v-for="(item, index) in form.promotionMerchantList"
            :key="index"
          >
            <div class="lists sk" style="width:37%">
              <div class="name" style="width:200px">商户新增数量</div>
              <div class="zhi">
                <el-input
                @input="value=>{item.minCnt=value.replace(/[^\d]+/g,'')}"
                  :disabled="dis == 'y'"
                  v-model="item.minCnt"
                  style="width: 145px"
                  placeholder="请输入内容"
                  maxlength="9"
                ></el-input
                >&nbsp;-&nbsp;
                <el-input
                @input="value=>{item.maxCnt=value.replace(/[^\d]+/g,'')}"
                  :disabled="dis == 'y'"
                  v-model="item.maxCnt"
                  style="width: 145px"
                  placeholder="请输入内容"
                  maxlength="9"
                ></el-input
                >人
              </div>
            </div>
            <!-- <div class="list sk">
          <div class="name">最少用户数量</div>
          <div class="zhi">
            <el-input v-model="item.cuNuma" style="width:145px" placeholder="请输入内容"></el-input>&nbsp;-&nbsp;
            <el-input v-model="item.cuNumb" style="width:145px" placeholder="请输入内容"></el-input>
          </div>
        </div> -->
            <div class="lists" style="width:23% !important">
              <div class="name" style="width:100px">最低交易金额</div>
              <el-input
                class="jiaoyi"
                :disabled="dis == 'y'"
                v-model="item.totalAmt"
                style="width: 150px"
                maxlength="9"
                @input="value=>{item.totalAmt=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}"
                placeholder="请输入内容"
              ></el-input
              >元
            </div>
            <div class="lists">
              <div class="name" style="width:100px">奖励金额</div>
              <el-input
                :disabled="dis == 'y'"
                class="jiangli"
                @input="value=>{item.rewardAmt=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}"
                v-model="item.rewardAmt"
                maxlength="9"
                style="width: 150px"
                placeholder="请输入内容"
              ></el-input
              >元
              
            </div>
            <span
                type="primary"
                style="margin-left: 20px;margin-top:6px;color:#409EFF"
                @click="addSection"
                v-if="index == 0 && dis!='y'"
                >添加奖励区间</span
              >
              <img
                v-if="index != 0 && index == form.promotionMerchantList.length-1"
                class="delList"
                @click="detail(index)"
                src="../../assets/images/del.png"
                alt=""
              />
          </div>
        </div>
        <div class="btnGroup">
          <el-button type="primary" @click="bank">下一步</el-button>
          <el-button @click="banks">取消</el-button>
          <!-- <button @click="dian">点击</button> -->
        </div>
      </div>
    </div>
    <el-dialog
      title="规则说明"
      :visible.sync="dialogVisible3"
      width="800px"
      :before-close="handleClose"
    >
      <el-row>
        <el-form label-width="100px">
          <el-form-item label="活动说明：">普通代理新增拓展商户拉新活动，拓展的商户已绑定终端关系后，商户的交易量达标后给与奖励。</el-form-item>
          <el-form-item label="考核时间：">考核时间是活动总时间;普通代理参与活动有效期起止时间。</el-form-item>
          <el-form-item label="奖励规则：">满足拓展新增商户数，每个新增商户最低交易额达到规则要求，则普通代理获取奖励金额。<br/>如设置多个规则，单个普通代理如都完成规则，按照最高等级的奖励，只奖励一次。</el-form-item>
          <el-form-item label="奖励方式：">统一结算，指定日期入账</el-form-item>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible3 = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Littlehow } from "../../assets/js/util";
import axios from "axios";
import https from '../../plugins/https';
export default {
  data() {
    return {
      diss:false,
      dialogVisible3:false,
      value: "",
      value1: "",
      value2: "",
      options: [],
      options1: [],
      options2: [],
      disabled: true,
      optionsBrandTypeNum: [],
      brandId: null,

      promotionMerchantList: [],
      //提交的内容
      form: {
        //活动规则
        promotionMerchantList: [
          {
            minCnt: null,
            maxCnt: null,
            totalAmt: "",
            rewardAmt: ""
          }
        ],
        timers:[],
        productNoList: [],
        // Brand:"",
        activeName: "",
        startDate: "",
        endDate: "",
        officeUid: "",
        activeUid: "",
        objectType: "",
        officeUids: [],
        rewardDate: "",
        channelUid: null,
        Brand: [],
        producttUid: [],
        BrandTypeNum: []
      },
      // 目标
      targetUser: [
        // 促活商户数量a,b
        {
          cuNuma: "", //商户数量
          cuNumb: "", //商户数量
          smallMoney: "", //最低交易金额
          smallMoneyNum: "", //最低交易笔数
          rewardMoneyTarget: "" //奖励金额
        }
      ],
       // 时间选择
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      value1: "",
      //   考核结束
      rewardTimer: "", //奖励发放时间
      //   参与活动品牌
      optionsBrand: null,
      participate: "",
      // 品牌类型
      brandTypeS: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        },
        {
          value: "选项3",
          label: "蚵仔煎"
        },
        {
          value: "选项4",
          label: "龙须面"
        },
        {
          value: "选项5",
          label: "北京烤鸭"
        }
      ],
      objectType: [
        { label: "个人", value: "0" },
        { label: "团队", value: "1" }
      ],
      brandType: "",
      // 商品型号
      modelGroup: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        },
        {
          value: "选项3",
          label: "蚵仔煎"
        },
        {
          value: "选项4",
          label: "龙须面"
        },
        {
          value: "选项5",
          label: "北京烤鸭"
        }
      ],
      model: "",
      dis: "",
      diss: ""
    };
  },
  activated(){
    this.diss=false
    this.dis = this.$route.query.dis;
    this.disNo = this.$route.query.isSshow;
    // alert(this.disNo)
    if(this.$route.query.bools){
      this.form= {
        promotionMerchantList: [
          {
            minCnt: null,
            maxCnt: null,
            totalAmt: "",
            rewardAmt: ""
          }
        ],
        timers:[],
        productNoList: [],
        // Brand:"",
        activeName: "",
        startDate: "",
        endDate: "",
        officeUid: "",
        activeUid: "",
        objectType: "",
        officeUids: [],
        rewardDate: "",
        channelUid: null,
        Brand: [],
        producttUid: [],
        BrandTypeNum: []
      }
    }
    let uid = this.$route.query.uid;
    if (uid) {
      this.diss=true
      //如果uid存在调用回显
      this.echoData();
    } else {
      this.form.objectType = "0";
    }
  },
  created() {
    // alert(12)
  https.getAllOfficeLista({})
      .then(res => {
        console.log(res.data.data);
        let datas = res.data.data;
        datas.map(item => {
          item.label = item.name;
          item.value = item.uid;
        });
        //  
        var format = {
          id: "uid", //菜单编号，作为树形查找id
          root: "", //顶层节点的parentId是root
          pid: "parentUid", //父节点标识字段为parentId
          child: "children", //构造出的树形子节点数组名为children
          sort: { field: "sortNo", direct: 1 }
        }; //排序字段为sortNo，且正序
        console.log(Littlehow.tree.format(datas, format));
        console.log();
        var result = Littlehow.tree.format(datas, format);
        this.options = result;
        console.log(this.options);
      })
      .catch(err => {
        // alert("洒进来的咖啡机啦");
      });
    this.getList1();
    let uid = this.$route.query.uid;
    this.dis = this.$route.query.dis;
    this.diss = this.$route.query.diss;
    if (uid) {
      //如果uid存在调用回显
      this.echoData();
    } else {
      this.form.objectType = "0";
    }
  },
  mounted() {
    // let dd = document.getElementById
  },
  methods: {
    relues() {
      this.dialogVisible3 = true;
    },
    // 全选
    selectAll() {
      // alert(JSON.stringify(this.optionsBrandTypeNum))
      //  if (this.form.BrandTypeNum.length < this.optionsBrandTypeNum.length) {
      this.form.BrandTypeNum = [];
      //  alert(this.optionsBrandTypeNum.length)
      // alert(this.form.BrandTypeNum.length)
      // return
      if(this.dis!="y"){
        if (this.form.BrandTypeNum.length < this.optionsBrandTypeNum.length) {
          if(this.diss!=true){
        // alert("多选执行")
          var allOption = [];
          for (var i = 0; i < this.optionsBrandTypeNum.length; i++) {
            allOption.push(this.optionsBrandTypeNum[i].productUid);
          }
          this.$set(this.form, "BrandTypeNum", allOption);
          console.log("下面是全选以后后端需要的数据");
          console.log(this.form.BrandTypeNum);
          this.xingType(this.form.BrandTypeNum);
          this.$forceUpdate();
        }} else {
          // alert("取消多选执行")
          var allOption = [];
          this.$set(this.form, "BrandTypeNum", allOption);
          this.xingType(this.form.BrandTypeNum);
          this.$forceUpdate();
        }
      }else{
        this.form.BrandTypeNum=this.form.BrandTypeNum
        var allOption = [];
        //   this.$set(this.form, "BrandTypeNum", allOption);
        //   this.xingType(this.form.BrandTypeNum);
        //   this.$forceUpdate();
      }
      

      //  alert(JSON.stringify(this.form.BrandTypeNum))
      // this.optionsBrandTypeNum.map((item) => {
      //   alert(item)
      //   this.form.BrandTypeNum.push(item.name)
      // })
      //
      //  } else {
      //    this.form.BrandTypeNum = []
      //  }
    },
    delTag() {
      return false;
    },

    daterangeChange(e) {
      let _this = this;
      console.log(e);
      _this.$nextTick(() => {
        _this.$set(_this.form, "timers", [e[0], e[1]]);
        _this.$forceUpdate();
      });
      this.form.startDate = e[0];
      this.form.endDate = e[1];
    },

    //下拉列表商品接口
    getList1() {
      let oemUid = localStorage.getItem("uid");
      https.queryChannelNameList({ oemUid: oemUid })
        .then(res => {
          console.log("品品牌");
          console.log(res.data.data);
          this.optionsBrand = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取回显数据
    echoData() {
      let uid = this.$route.query.uid;
      https.queryUpdateActive({ activeUid: uid })
        .then(res => {
          // this.form.totalAmt = res.data.data.activeBrandOfficeTop[0].totalAmt;
          console.log(res);

          this.form = res.data.data;
          this.form.timers = [];
          this.form.BrandTypeNum = [];
          // this.form.timers.push(res.data.data.startDate);
          // this.form.timers.push(res.data.data.endDate);

          var arr = [];
          arr.push(res.data.data.startDate);
          arr.push(res.data.data.endDate);
          this.$set(this.form, "timers", arr);

          // this.form.totalAmt = res.data.data.activeBrandOfficeTop[0].totalAmt;
          this.form.channelUid = res.data.data.productNoList[0].channelUid;
          this.form.Brand = res.data.data.productNoList[0].channelUid;
          this.form.productNoList.channelUid = this.form.Brand;
          this.pinChange(this.form.Brand);
          https.activeBrand({
              brandChannelId: this.form.Brand
            })
            .then(res1 => {
              this.optionsBrandTypeNum = res1.data.data;
              console.log(this.optionsBrandTypeNum);
              var temps = [];
              //拿到数组里面的来进行赋值操作
              for (let i = 0; i < res.data.data.productNoList.length; i++) {
                // temps.push()
                temps.push(res.data.data.productNoList[i].productUid);
              }
              this.form.BrandTypeNum = temps;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(err => {
          console.log(err);
        });
    },
    //根据品牌id请求商品
    pinChange(val) {
      // alert(val)
      // this.form.BrandTypeNum = [];
      console.log("id是");
      this.form.BrandTypeNum = [];
      console.log(val);
      //品牌id
      this.brandId = val;
      var ids = this.form.Brand;

      //根据品牌获取商品
      https.activeBrand({ brandChannelId: val })
        .then(res => {
          console.log("这里");
          console.log(res);
          // this.BrandTypeNum = res.data.data
          this.optionsBrandTypeNum = res.data.data;
          //
          // var uid = this.$route.query.uid;
          // if(uid){
          //   alert("进入")
          //   this.hui()
          // }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // hui(){
    //   for (let i = 0; i < res.data.data.productNoList.length; i++) {
    //       //  alert(res.data.data.productNoList[i].productUid)
    //       this.form.BrandTypeNum.push(
    //         res.data.data.productNoList[i].productUid
    //       )
    //     }
    // },
    xingType(val) {
      console.log(val);
      // return

      const length = val.length;
      this.form.productNoList = [];
      console.log("下面是val");
      console.log(val);
      for (var i = 0; i < length; i++) {
        this.form.productNoList.push({
          channelUid: this.brandId,
          productUid: val[i]
        });
      }
      console.log("下面是需要用到的");
      console.log(this.form.productNoList);
    },
    // delData(val){
    //   // alert(val)
    //   console.log("看val")
    //   console.log(val)
    //   // return
    //   const length = val.length
    //   this.form.productNoList = []
    //   this.form.productNoList.push({
    //     channelUid:this.brandId,
    //     productUid:val[length - 1]
    //   })
    //   console.log("信息是下面")
    //   console.log(this.form.productNoList)
    // },

    addSection() {
      this.form.promotionMerchantList.push({
        minCnt: null,
        maxCnt: null,
        totalAmt: "",
        rewardAmt: ""
      });
    },
    detail(num) {
      if(this.$route.query.dis!="y"){
        this.form.promotionMerchantList.splice(num, 1);
      }
      
    },
    banks() {
      this.$router.push({
        path: "activityManagement",
        type: "savePromotionMerchantActive"
      });
    },
    dian() {
      this.form.startDate = this.form.kaoTime[0];
      this.form.endDate = this.form.kaoTime[1];
      console.log(this.form.noActive);
      this.form.noActiveStart = this.form.noActive[0];
      this.form.noActiveSEnd = this.form.noActive[1];
      // alert(this.form.kaoTime)
      // // 提交的时候要
      // this.form.kaoTime.split(",")
      // alert(JSON.stringify(this.form.kaoTime))
    },

    isDuringDate(beginDateStr, endDate) {
      var curDate = new Date(),
        beginDate = new Date(beginDateStr),
        endDate = new Date(endDate);
      if (this.form.rewardDate > this.form.endDate) {
        return false;
      } else {
        return true;
      }
    },

    bank() {
      if (this.form.activeName == "")
        return layer.open({
          content: "活动名称不能未空",
          skin: "msg",
          time: 2
        });
        if(this.form.Brand==""){
        return layer.open({
          content: "活动品牌不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }
      if(this.form.productNoList.length==0){
        return layer.open({
          content: "活动商品不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }
      if (this.form.timers.length < 2)
      return layer.open({
          content: "考核时间不能未空",
          skin: "msg",
          time: 2
        });
         if (this.form.rewardDate == "")
      return layer.open({
          content: "奖励发放时间",
          skin: "msg",
          time: 2
        });
      this.$store.commit("clearSetActiveRanking");
      this.$store.commit("clearSetBannerData");
      this.$store.commit("clearSetBingImg");

      console.log(this.form);
      // return
      this.form.endDate; //pasdfsdfasdsssssssss
      this.form.rewardDate; //
      if (this.isDuringDate(this.form.endDate, this.form.rewardDate) != true) {
        this.$store.commit("setActiveRanking", this.form);
        //  
        for (let i = 0; i < this.form.promotionMerchantList.length; i++) {
          this.form.promotionMerchantList[i].minCnt = Number(
            this.form.promotionMerchantList[i].minCnt
          );
          this.form.promotionMerchantList[i].maxCnt = Number(
            this.form.promotionMerchantList[i].maxCnt
          );
          if( this.form.promotionMerchantList[i].totalAmt==0){
             return layer.open({
              content: "交易金额不能为0",
              skin: "msg",
              time:  2 //1秒后自动关闭
            });
          }
        }

        // let uid = this.$route.query.uid
        this.$router.push({
          path: "nextActive",
          query: {
            type: "savePromotionMerchantActive",
            uid: this.$route.query.uid,
            user: this.$route.query.dis,
            name:"teamRewardfrind"
          }
        });
      } else {
        return layer.open({
          content: "奖励发放时间要大于活动结束时间",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      
        // alert("奖励发放时间要大于活动结束时间");
      }
    },
    shijian(val) {
      this.form.startDate = val[0];
      this.form.endDate = val[1];
    }
  }
};
</script>

<style scoped>
.con {
  position: relative;
}
/* 取消tag的删除功能 */
/deep/ .el-tag__close {
  display: none !important;
}
.wrap {
  width: 96%;
  margin: 0 auto;
}
.listWrap {
  display: flex;
  float: left;
  /* margin-left: -77px; */
  flex-wrap: wrap;
}
.lists {
  display: flex;
  align-items: center;
  /* width: 33.3333%; */
  /* width: 450px; */
  margin-bottom: 20px;
}
.list {
  display: flex;
  align-items: center;
  /* width: 33.3333%; */
  width: 450px;
  margin-bottom: 20px;
}
.name {
  width: 100px;
  text-align: right;
  margin-right: 10px;
}
.topTitle {
  font-size: 16px !important;
  /* font-weight: bold; */
  /* margin-bottom: 30px; */
  margin-top: 20px;
}
.subTitle {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
}
.target {
  display: flex;
  flex-wrap: wrap;
}
.target .list {
  width: 33.3333%;
  justify-content: left;
}
.queryMerchants {
  height: 60px;
  margin-top: 15px;
  margin-bottom: 30px;
  line-height: 60px;
  text-indent: 20px;
  background: #f5f7fa;
}
.zhi {
  display: flex;
  align-items: center;
}
.targetSet {
  width: 1200px;
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  /* margin-left: -30px; */
  /* margin-top: 40px; */
}
.targetSet .lists {
  /* width: 33%; */
  display: flex;
}
/deep/ .el-input__inner {
  width: 300px;
}
/deep/ .el-input {
  width: 300px;
}
/deep/ .el-popper {
  width: 300px;
}
@media screen and (max-width: 1360px) {
  .targetSet .list {
    width: 100% !important;
  }
}
.delList {
  width: 20px;
  height: 20px;
  margin-left: 20px;
  margin-top: 5px;
  cursor: pointer;
}
.btnGroup {
  margin-top: 30px;
  float: left;
  /* width: 100%; */
  margin-top: 50px;
  margin-left: 40%;
  margin-bottom: 20px
}
/deep/ .el-range-separator {
  width: 50px;
}
.sk .el-input {
  width: 150px !important;
}
/deep/ .sk .el-input__inner {
  width: 150px;
}
.targetsUser {
  font-size: 16px;
  color: #303133;
}
.subTitle {
  font-size: 16px;
  color: #303133;
}
/deep/ .jiaoyi .el-input__inner {
  width: 150px;
}
/deep/ .jiangli .el-input__inner {
  width: 150px;
}
/* 单独样式 */
.contbox6_10 {
  width: 100%;
  /* margin-left: 2%; */
  /*  height: 87.5vh; */
  overflow-x: auto;
  box-sizing: border-box;
  float: left;
}
.jibenInfo {
  width: calc(100% - 40px);
  margin: 0 20px 20px;
  height: 40px;
  line-height: 40px;
  float: left;
  font-size: 18px;
}
.relus {
  width: 100%;
  height: 30px;
  line-height: 30px;
  padding-left: 20px;
  background: #f9f4f7;
  /* color: #fb932b; */
}
</style>
